package com.coco.thread.stop;

/**
 * 停止线程 使用终止标识，不建议使用stop 因为stop 等方法在停止的时候会直接终止，造成没有执行完成的任务
 * 不能够即时释放资源。
 *                       thread.interrupt()  给线程标记为一个停止状态
 * 判断该线程是否为标记了终止状态：
 * Thread.currentThread().isInterrupted()  判断标识，true标识被标记了停止标识
 *                        isInterrupted()  判断标识，true标识被标记了停止标识
 *                   thread.interrupted() 判断标识，true标识被标记了停止标识，但是这个方法会把true改为false
 *
 */
public class ThreadStop {

    static class MyRunnable implements Runnable{

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()){
                System.out.println(Thread.currentThread().getName()+" ---- "+Thread.currentThread().isInterrupted());
            }
        }
    }

    /**
     * Thread.interrupted() 方法调用后会把 标记为true 改为false
     */
    public static class MyThread extends Thread{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" ---- "+Thread.interrupted());
            System.out.println(Thread.currentThread().getName()+" ---- "+Thread.interrupted());
        }
    }

    public static class Test3Thread extends Thread{
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " ---- " + isInterrupted());
                } catch (InterruptedException e) {
                    //如果出现异常，要给进程标记为停止。否则进程会继续执行新的任务。
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }

            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
//            test1();
//            test2();
               test3();
    }

    private static void test1()throws InterruptedException{
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable,"coco-test1");
        thread.start();
        Thread.sleep(30);
        thread.interrupt();//给线程标记一个停止的状态 true
    }

    private static void test2()throws InterruptedException{
        MyThread myThread = new MyThread();
        myThread.setName("小咪-test2");
        myThread.start();
        myThread.interrupt();//给线程标记一个停止的状态 true
    }

    private static void test3()throws InterruptedException{
        Test3Thread myThread = new Test3Thread();
        myThread.setName("小咪-test3");
        myThread.start();
        Thread.sleep(3000);
        myThread.interrupt();//给线程标记一个停止的状态 true
    }


}
